﻿using LockerRack;
using LockerRack.Exceptions;
using Microsoft.Practices.Unity;
using TasksLib.Resolvers;

namespace UIController.Controllers
{
    public class TaskModelController : ITaskController
    {
        private static ITaskController _controller;
        private Locker _locker;
        private IUnityContainer _container;

        public Locker Locker
        {
            get { return _locker; }
        }

        public IUnityContainer TypesContainer
        {
            get { return _container; }
        }

        public static ITaskController GetInstance()
        {
            if(_controller == null)
                _controller = new TaskModelController();

            return _controller;
        }

        public bool Initialize(string workingPath, out LockerException ex)
        {
            Clear(false, out ex);
            if (ex != null)
                return false;

            LockerException lex;
            TaskFileResolver resolver = new TaskFileResolver();
            _container = resolver.Container;
            _locker = Locker.OpenLocker(workingPath, resolver.Container, out lex);

            if(_locker == null || lex != null)
            {
                ex = lex;
                return false;
            }

            return true;
        }

        public void Clear(bool saveOnExit, out LockerException ex)
        {
            ex = null;
            if (_locker != null)
            {
                if(saveOnExit)
                {
                    _locker.SaveLocker(out ex);
                }
                _locker.CloseLocker();
                _locker.Dispose();
                _locker = null;
            }
        }

        public void Dispose()
        {
            LockerException ex;
            Clear(false, out ex);
            _controller = null;
        }
    }
}
